/**
 * 
 */
package cn.touch.demo.hibernate.basic;

import java.sql.SQLException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;

/**
 * Dec 4, 2014
 *
 * @author <a href="mailto:touchnan@gmail.com">chegnqiang.han</a>
 */
public class BasicDemo {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws SQLException {
        User user = new User();
        // Note: id generated by Hibernate
        user.setName( "Brett Meyer" );
        user.setEmail( "foo@foo.com" );
        user.setPhone( "123-456-7890" );
        
        insertUser( user );  
        user = getUser(user.getId());
        System.out.println( user.toString() );
        System.exit(0);
    }
    
    private static void insertUser(User user) throws SQLException {
        Session session = openSession();
        session.getTransaction().begin();
        session.persist( user ); // cascades the tool & skill relationships
        session.getTransaction().commit();
    }
    
    private static User getUser(int id) throws SQLException {
        Session session = openSession();
        
        User user = (User) session.get( User.class, id );
        
//      Query query = session.createQuery( "SELECT u FROM User u WHERE u.id=:id" );
//      query.setParameter( "id", id );
//      User user = (User) query.uniqueResult();
        
//      User user = (User) session.createCriteria( User.class )
//              .add( Restrictions.eq( "id", id ) )
//              .uniqueResult();
        
        session.close();
        
        return user;
    }    
    
    private static SessionFactory sessionFactory = null;
    private static Session openSession() {
        if (sessionFactory == null) {
            final Configuration configuration = new Configuration();
            configuration.addAnnotatedClass( User.class );
            sessionFactory = configuration.buildSessionFactory( new StandardServiceRegistryBuilder().build() );
        }
        return sessionFactory.openSession();
    }

}
